<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\CaptchaRequest;
use App\Http\Requests\Api\PhoneRequest;
use Gregwar\Captcha\CaptchaBuilder;
use Overtrue\EasySms\EasySms;

class UsersController extends ApiController
{
    /**
     * @param PhoneRequest $request
     * @param CaptchaBuilder $captchaBuilder
     * @return mixed
     */
    public function captureShow(PhoneRequest $request,CaptchaBuilder $captchaBuilder)
    {
        $phone=$request->phone;
        $captchaKey='captcha-'.str_random(15);
        //生成api图片验证码
        $captcha=$captchaBuilder->build();
        //生成图片地址
        $captchaUrl=$captcha->inline();
        $captchaValue=$captcha->getPhrase();
        $expiredAt=now()->addMinutes(10);
        \Cache::put($captchaKey,['phone'=>$phone,'captcha'=>$captchaValue],$expiredAt);

        $result=[
          'capcha_key'=>$captchaKey,
          'expired_at'=>$expiredAt,
          'captcha_image_content'=>$captchaUrl
        ];
        return $this->response->array($result)->setStatusCode(201);
    }

    public function verifyCodes(CaptchaRequest $request,EasySms $EasySms)
    {
        $cacheKey=$request->captcha_key;
        $code=$request->captcha_code;
        $value=\Cache::get($cacheKey);
        if(!$value){
          return $this->response->errorForbidden('缓存不存在或已过期');
        }
        if(!hash_equals($code,$value['code'])){
          \Cache::forget($capcha_key);
          return $this->response->errorUnauthorized('验证码不正确');
        }
        // 发送短信
        $phone=$value['phone'];
        $code=str_pad(random_int(1, 9999),4,0,STR_PAD_LEFT);
        if($phone){
          try{

          }catch(NoGatewayAvailableException $exception){
              $message=$exception->getException('aliyun')->getMessage();
          }
        }
        // 存入缓存
        return $value;
    }
}
